package conf

import (
	"encoding/json"
	"io/ioutil"
	"sync"

	"gitee.com/cloudapex/ulern/cto"
	"gitee.com/cloudapex/ulern/util"
)

type QiNiuSetting struct {
	AccessKey string `json:"accessKey"`
	SecretKey string `json:"secretKey"`
	Bucket    string `json:"bucket"`
}

//------------------------------------------------------------------------------
//=====================================Qiniu====================================
//------------------------------------------------------------------------------
var Qiniu *qiniuConf

func init() { Qiniu = cto.Preload("MT_Qiniu", &qiniuConf{}).(*qiniuConf) }

type qiniuConf struct {
	mutx sync.Mutex
	main *mainQiniu
}
type mainQiniu struct {
	Param QiNiuSetting `json:"param"`
}

func (this *qiniuConf) HandleInit() error {
	this.main = &mainQiniu{}
	data, err := ioutil.ReadFile(this.HandlePath())
	if err != nil {
		return err
	}
	return json.Unmarshal(data, this.main)
}
func (this *qiniuConf) HandlePath() string { return util.ExePathJoin("confs/qiniu.json") }

func (this *qiniuConf) HandleContent() string {
	b, err := json.MarshalIndent(this.main, "", "\t")
	if err != nil {
		return err.Error()
	}
	return string(b)
}
func (this *qiniuConf) HandleReload() error {
	data, err := ioutil.ReadFile(this.HandlePath())
	if err != nil {
		return err
	}

	temp := &mainQiniu{}
	if err := json.Unmarshal(data, temp); err != nil {
		return err
	}
	defer util.UnLock(util.Lock(&this.mutx))
	// update some fields
	return cto.ErrSettingNotNeed
}

//------------------------------------------------------------------------------
//================================开放方法=======================================
//------------------------------------------------------------------------------
func (this *qiniuConf) Stg() *mainQiniu {
	defer util.UnLock(util.Lock(&this.mutx))
	return this.main
}
